using System;
using System.Net;

namespace Lazy.Captcha.Core.RateLimit
{
    /// <summary>
    /// 频率限制扩展方法
    /// </summary>
    public static class RateLimitExtensions
    {
        /// <summary>
        /// 根据策略生成频率限制键
        /// </summary>
        /// <param name="strategy">键策略</param>
        /// <param name="ipAddress">IP地址</param>
        /// <param name="userId">用户ID</param>
        /// <param name="customKey">自定义键</param>
        /// <returns></returns>
        public static string GenerateRateLimitKey(this RateLimitKeyStrategy strategy, 
            string ipAddress = null, string userId = null, string customKey = null)
        {
            return strategy switch
            {
                RateLimitKeyStrategy.IpAddress => $"captcha_rate_limit:ip:{ipAddress ?? "unknown"}",
                RateLimitKeyStrategy.UserId => $"captcha_rate_limit:user:{userId ?? "anonymous"}",
                RateLimitKeyStrategy.Custom => $"captcha_rate_limit:custom:{customKey ?? "default"}",
                _ => $"captcha_rate_limit:default:{ipAddress ?? "unknown"}"
            };
        }

        /// <summary>
        /// 从 IP 地址字符串生成频率限制键
        /// </summary>
        /// <param name="ipAddress">IP地址字符串</param>
        /// <returns></returns>
        public static string ToRateLimitKey(this string ipAddress)
        {
            return RateLimitKeyStrategy.IpAddress.GenerateRateLimitKey(ipAddress: ipAddress);
        }

        /// <summary>
        /// 从 IPAddress 对象生成频率限制键
        /// </summary>
        /// <param name="ipAddress">IPAddress对象</param>
        /// <returns></returns>
        public static string ToRateLimitKey(this IPAddress ipAddress)
        {
            return ipAddress?.ToString().ToRateLimitKey() ?? "unknown".ToRateLimitKey();
        }

        /// <summary>
        /// 检查频率限制结果是否表示被限制
        /// </summary>
        /// <param name="result">频率限制结果</param>
        /// <returns></returns>
        public static bool IsRateLimited(this RateLimitResult result)
        {
            return !result.IsAllowed;
        }

        /// <summary>
        /// 获取到下次重置的剩余秒数
        /// </summary>
        /// <param name="result">频率限制结果</param>
        /// <returns></returns>
        public static int GetSecondsUntilReset(this RateLimitResult result)
        {
            if (!result.ResetTime.HasValue)
                return 0;

            var remaining = result.ResetTime.Value - DateTime.UtcNow;
            return Math.Max(0, (int)remaining.TotalSeconds);
        }
    }
}
